package com.wty.app.bthcar;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;

import com.tbruyelle.rxpermissions3.RxPermissions;
import com.wty.app.bthcar.R;
import com.wty.app.bthcar.bluetooth.BluetoothChatService;
import com.wty.app.bthcar.bluetooth.DeviceListActivity;
import com.wty.app.bthcar.utils.PreferenceUtil;
import com.wty.app.bthcar.view.RockerView;

import io.reactivex.rxjava3.functions.Consumer;
import rx.functions.Action1;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.BLUETOOTH;
import static android.Manifest.permission.BLUETOOTH_ADMIN;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private ImageButton btnback;
    private ImageButton btngo;
    private ImageButton btnleft;
    private ImageButton btnright;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothChatService mChatService = null;
    private String mConnectedDeviceName = null;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override // android.os.Handler
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    switch (msg.arg1) {
                        case 2:
                            Toast.makeText(MainActivity.this.getApplicationContext(), "正在连接该蓝牙设备", Toast.LENGTH_SHORT).show();
                            return;
                        case 3:
                        default:
                            return;
                    }
                case 2:
                    new String((byte[]) msg.obj, 0, msg.arg1);
                    return;
                case 3:
                    String writeMessage = new String((byte[]) msg.obj);
                    String result = "";
                    if (writeMessage.equals(PreferenceUtil.getInstance().getStopCode())) {
                        result = "停车";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getLeftCode())) {
                        result = "左转";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getRightCode())) {
                        result = "右转";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getUpCode())) {
                        result = "前进";
                    } else if (writeMessage.equals(PreferenceUtil.getInstance().getDownCode())) {
                        result = "后退";
                    }
                    Log.d("蓝牙小车:", result);
                    return;
                case 4:
                    MainActivity.this.mConnectedDeviceName = msg.getData().getString(BluetoothChatService.DEVICE_NAME);
                    Toast.makeText(MainActivity.this.getApplicationContext(), "连接上 " + MainActivity.this.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    return;
                case 5:
                    Toast.makeText(MainActivity.this.getApplicationContext(), msg.getData().getString(BluetoothChatService.TOAST), Toast.LENGTH_SHORT).show();
                    return;
                default:
                    return;
            }
        }
    };
    private ImageButton settings;
    TextView tv_setting;
    private RockerView recLeft;
    private RadioGroup group;

    /* access modifiers changed from: protected */
    @SuppressLint("CheckResult")
    @Override // android.support.v7.app.AppCompatActivity, android.support.v4.app.FragmentActivity, android.support.v4.app.BaseFragmentActivityDonut, android.app.Activity
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        }
        getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_main);
        this.settings = (ImageButton) findViewById(R.id.settings);
        this.btngo = (ImageButton) findViewById(R.id.btngo);
        this.btnleft = (ImageButton) findViewById(R.id.btnleft);
        this.btnright = (ImageButton) findViewById(R.id.btnright);
        this.btnback = (ImageButton) findViewById(R.id.btnback);
        group = findViewById(R.id.group);
        recLeft = findViewById(R.id.rockerView_left);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.group_1:
                        sendMessage("c");
                        break;
                    case R.id.group_2:
                        sendMessage("d");
                        break;
                    case R.id.group_3:
                        sendMessage("e");
                        break;
                }
            }
        });


        SwitchCompat ledBtn = findViewById(R.id.led_btn);
        ledBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    sendMessage("a");
                }else {
                    sendMessage("b");
                }
            }
        });
        this.tv_setting = (TextView) findViewById(R.id.tv_setting);
        initListener();
        this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (this.mBluetoothAdapter == null) {
            Toast.makeText(this, "手机无蓝牙设备", Toast.LENGTH_SHORT).show();
        } else if (this.mBluetoothAdapter.isEnabled()) {
            this.mChatService = new BluetoothChatService(this, this.mHandler);
        } else if (Build.VERSION.SDK_INT >= 23) {
            RxPermissions rxPermissions = new RxPermissions(this);

            rxPermissions.request(BLUETOOTH,BLUETOOTH_ADMIN,ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Throwable {
                    if (aBoolean) {
                        MainActivity.this.startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 2);
                    }
                }
            });
        } else {
            startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), 2);
        }
    }

    /* access modifiers changed from: protected */
    @Override // android.support.v4.app.FragmentActivity, android.app.Activity
    public void onResume() {
        super.onResume();
        if (this.mChatService != null && this.mBluetoothAdapter != null && this.mBluetoothAdapter.isEnabled() && this.mChatService.getState() == 0) {
            this.mChatService.start();
        }
    }

    @Override // android.support.v7.app.AppCompatActivity, android.support.v4.app.FragmentActivity, android.app.Activity
    public void onDestroy() {
        super.onDestroy();
        if (this.mChatService != null) {
            this.mChatService.stop();
        }
        if (this.mBluetoothAdapter != null && this.mBluetoothAdapter.isEnabled()) {
            this.mBluetoothAdapter.disable();
        }
    }



    @Override // android.support.v4.app.FragmentActivity, android.app.Activity
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == -1) {
                    BluetoothDevice device = this.mBluetoothAdapter.getRemoteDevice(data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS));
                    if (this.mChatService == null) {
                        this.mChatService = new BluetoothChatService(this, this.mHandler);
                        this.mChatService.start();
                    }
                    this.mChatService.connect(device);
                    return;
                }
                return;
            case 2:
                if (resultCode == -1) {
                    Toast.makeText(this, (int) R.string.bt_enabled_success, Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, (int) R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
                return;
            default:
                return;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {

        recLeft.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
        recLeft.setOnShakeListener(RockerView.DirectionMode.DIRECTION_4_ROTATE_45, new RockerView.OnShakeListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void direction(RockerView.Direction direction) {
                String message = "";
                switch (direction) {
                    case DIRECTION_LEFT:
                        message = "左转";
                        MainActivity.this.sendMessage(PreferenceUtil.getInstance().getLeftCode());
                        break;
                    case DIRECTION_RIGHT:
                        message = "右转";
                        MainActivity.this.sendMessage(PreferenceUtil.getInstance().getRightCode());
                        break;
                    case DIRECTION_UP:
                        message = "前进";
                        MainActivity.this.sendMessage(PreferenceUtil.getInstance().getUpCode());
                        break;
                    case DIRECTION_DOWN:
                        message = "后退";

                        MainActivity.this.sendMessage(PreferenceUtil.getInstance().getDownCode());
                        break;
                    case DIRECTION_CENTER:
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFinish() {
                sendMessage("5");
            }
        });

        this.btngo.setOnTouchListener(new View.OnTouchListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass2 */

            @Override // android.view.View.OnTouchListener
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case 0:
                        MainActivity.this.btngo.setBackgroundResource(R.mipmap.up_press);
                        sendMessage("8");
                        return false;
                    case 1:
                        MainActivity.this.btngo.setBackgroundResource(R.mipmap.up);
                        MainActivity.this.sendMessage("0");
                        return false;
                    default:
                        return false;
                }
            }
        });
        this.btnleft.setOnTouchListener(new View.OnTouchListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass3 */

            @Override // android.view.View.OnTouchListener
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case 0:
                        MainActivity.this.btnleft.setBackgroundResource(R.mipmap.left_press);
                        sendMessage("6");
                        return false;
                    case 1:
                        MainActivity.this.btnleft.setBackgroundResource(R.mipmap.left);
                        MainActivity.this.sendMessage("0");
                        return false;
                    default:
                        return false;
                }
            }
        });
        this.btnright.setOnTouchListener(new View.OnTouchListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass4 */

            @Override // android.view.View.OnTouchListener
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case 0:
                        MainActivity.this.btnright.setBackgroundResource(R.mipmap.right_press);
                        sendMessage("7");
                        return false;
                    case 1:
                        MainActivity.this.btnright.setBackgroundResource(R.mipmap.right);
                        MainActivity.this.sendMessage("0");
                        return false;
                    default:
                        return false;
                }
            }
        });
        this.btnback.setOnTouchListener(new View.OnTouchListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass5 */

            @Override // android.view.View.OnTouchListener
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case 0:
                        MainActivity.this.btnback.setBackgroundResource(R.mipmap.back_press);
                        sendMessage("9");
                        return false;
                    case 1:
                        MainActivity.this.btnback.setBackgroundResource(R.mipmap.back);
                        MainActivity.this.sendMessage("0");
                        return false;
                    default:
                        return false;
                }
            }
        });
        this.settings.setOnClickListener(new View.OnClickListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass7 */

            @Override // android.view.View.OnClickListener
            public void onClick(View v) {
                MainActivity.this.startActivityForResult(new Intent(MainActivity.this, DeviceListActivity.class), 1);
            }
        });
        this.tv_setting.setOnClickListener(new View.OnClickListener() {
            /* class com.wty.app.bluetoothcar.MainActivity.AnonymousClass8 */

            @Override // android.view.View.OnClickListener
            public void onClick(View v) {
                MainActivity.this.startActivity(new Intent(MainActivity.this, CodeSetttingActivity.class));
            }
        });
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void sendMessage(String message) {
        if (this.mBluetoothAdapter == null) {
            Toast.makeText(this, "手机无蓝牙设备", Toast.LENGTH_SHORT).show();
        } else if (this.mChatService == null || this.mChatService.getState() != 3) {
            Toast.makeText(this, (int) R.string.not_connected, Toast.LENGTH_SHORT).show();
        } else if (message.length() > 0) {
//            this.mChatService.write(message.getBytes());
            this.mChatService.write(message.getBytes());
        }
    }
}
